package cn.com.dcsgo.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Objects;

/**
 * QPS日志记录过滤器
 * 将QPS信息写入到日志
 *
 * @author Dcsgo
 * @since 2025/9/20 13:41
 */
@Slf4j
@Component
public class QpsRecordsFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String ip = Objects.requireNonNull(request.getRemoteAddress()).getHostString();
        String api = request.getURI().getPath();
        log.info("HTTP请求,IP:{},API:{}", ip, api);
        return chain.filter(exchange);
    }

    /**
     * 最高优先级，在所有请求前执行
     */
    @Override
    public int getOrder() {
        return Integer.MIN_VALUE;
    }
}
